<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <div class="container">
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
    <button>按钮</button>
  </div>

  <script>
    /* 方法1：利用事件委托 */
    // var container = document.querySelector('.container')
    // var children = Array.prototype.slice.call(container.children)      

    // container.addEventListener('click',function(e){
    //     if(e.target.tagName === 'BUTTON'){
    //       var index = children.indexOf(e.target)
    //       console.log(index);
    //     }

    // })  


    /* 方法2：在循环中注册事件，利用立即执行函数 */

    var btns = document.querySelectorAll('button')
    console.log(btns);

    for (var i = 0; i < btns.length; i++) {
      (function (i) {
        btns[i].onclick = function () {
          console.log(i);
        }
      })(i)
    }

  </script>
</body>

</html>